import React from 'react';

export const asyncComponent = loadComponent => (
    class AsyncCompment extends React.Component {
        constructor(props) {
            super(props);
            this.state = {
                Component:null
            }

            this.hadLoadedComponent = this.hasLoadedComponent.bind(this)
        }

        componentWillMount(){
            if(this.hasLoadedComponent()){
                return
            }
        
            loadComponent()
                .then(module => module.default?module.default:module)
                .then(Component=>{
                    this.setState({
                        Component
                    })
                })
                .catch(e=>{
                    console.error('cannot load Component in <AsyncComponent>')
                    
                    throw e
                })
        }
        
        hasLoadedComponent(){
            return this.state.Component !== null;
        }
        
        render(){
            const { Component } = this.state
            const errorComponent = <div>异步加载组件失败</div>

            return (Component)?<Component {...this.props}/>:null
        }
        
    }
)